﻿
package extremefx.storage {
	import extremefx.events.EventHandler;
	
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundLoaderContext;		

	/**
	 * @author Marcelo Volmaro
	 */
	public class SoundLoader extends QeuedItem {
		private var _sound:Sound;

		public function SoundLoader(pUrl:*, pContext:SoundLoaderContext = null) {
			super(pUrl, pContext);
			_sound = null;
		}

		override public function start():Boolean {
			var r:Boolean = super.start();
			if (r){
				var snd:Sound = _sound = new Sound();
				_addHandlers(snd);
				snd.addEventListener(Event.ID3, _id3Handler, false, 0, true);
				snd.load(_loadUrl, SoundLoaderContext(_cnx));
			}
			
			return r;
		}
		
		private function _id3Handler(event:Event):void {
			if (_eOnID3Load) _eOnID3Load.fire(new ID3EventArgs(_sound.id3));
		}
		
		private var _eOnID3Load:EventHandler;
		public function get onID3Load():EventHandler{
			if (_eOnID3Load == null) _eOnID3Load = new EventHandler(this);
			return _eOnID3Load;
		}

		override public function stop():Boolean {
			var r:Boolean = super.stop();
			if (_sound) _sound.removeEventListener(Event.ID3, _id3Handler);
			if (r){
				try{
					_sound.close();
				} catch(error:Error){}
			}
			
			_sound = null;
			return r;
		}
		
		override public function dispose():void {
			super.dispose();
			if (_sound) _sound.removeEventListener(Event.ID3, _id3Handler);
			_sound = null;
		}
		

		public function get sound():Sound { 
			return _sound; 
		}
	}
}
